package ch.electronet.wjw.web.actions;

import java.util.Collection;

import net.sf.json.JsonConfig;

import org.apache.commons.collections.Closure;
import org.apache.commons.collections.CollectionUtils;

import ch.electronet.wjw.index.Index;
import ch.electronet.wjw.web.Picture;

import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

public class SearchAction extends JsonDataAction {

	private static final long serialVersionUID = 1L;

	// queryString
	private String q;

	private static int idCounter;

	@RequiredFieldValidator(type = ValidatorType.FIELD, message = "You must enter a query")
	public void setQ(String q) {
		this.q = q;
	}

	public String getQ() {
		return q;
	}

	private int newId() {
		return idCounter++;
	}

	@Override
	protected Object getData(JsonConfig config) {
		Collection<Picture> pictures = getPicturesIndex().search(q);
		idCounter = 0;
		CollectionUtils.forAllDo(pictures, new Closure() {
			public void execute(Object o) {
				((Picture) o).setId(newId());
			}
		});
		setStatus(pictures.size() + " pictures found");
		return pictures;
	}

	private Index<Picture> picturesIndex;

	public Index<Picture> getPicturesIndex() {
		return picturesIndex;
	}

	public void setPicturesIndex(Index<Picture> picturesIndex) {
		this.picturesIndex = picturesIndex;
	}

}
